#引数

setwd("/var/www/html/total/app/data/")

args <- commandArgs(trailingOnly=TRUE)

#axis <- args[1]

labelf <- args[1]
rawf <- args[2]
ofile <- paste("cross", args[3], ".txt", sep="")
axis <- args[4]

#rawf <- "rawdata-utf8.csv"
#labelf <- "label-utf8.csv"
#axis <- "q7"

labels <- read.csv(labelf, header=TRUE)
raws <- read.csv(rawf, header=TRUE)

axisl <- subset(labels, labels$la == axis)

#軸の設問タイプチェック
isMA <- FALSE
if (axisl$t == "SA") {
    isMA <- FALSE
} else if (axisl$t == "MA") {
    isMA <- TRUE
} else {
    stop("please check the axis. the type of the axis must be SA OR MA ")
}

axiscate <- axisl[9:length(axisl)]
axiscate <- axiscate[axiscate != ""]
#print(axiscate)

output <- file(ofile, open="w")

for ( i in 1:nrow(labels) ) {
    
    cate <- NULL
    tn <- NULL
    tp <- NULL

    label <- labels[i,]

    #サンプルNo列（設問タイプが空）とFAが対象外
    if (label$t == "" || label$t == "FA") {

    } else {
    
        #空行を出力
        cat("\n", file=output)

        print(paste(label$la, label$nm));
        #outf(paste(label$la, label$nm), file=output)
        cat(paste(label$la, label$nm), file=output, sep="\t")
        cat("\n", file=output)

        cate <- label[9:length(label)]
        cate <- cate[cate != ""]
        #print(cate)
    }
    
    if (label$t == "SA") {

        #軸がMA TODO
        if (isMA == TRUE) {
            for ( l in axisl$cno:axisl$cno2 ) {
                row <- NULL
                subraws = subset(raws, raws[, l] == 1)

                for (j in 1:length(cate)) {
                    row <- c(row, nrow(subset(subraws, subraws[,label$cno] == j)))
                }

                #合計（該当数、縦/行合計）
                #全数？
                #row <- c(row, nrow(subraws))
                #回答数？
                row <- c(row, nrow(subset(subraws, ! is.na(subraws[, label$cno]))))
                tn <- rbind(tn, row)
                
            }

            #横/列合計
            csum <- NULL
            for (j in 1:length(cate)) {
                csum <- c(csum, nrow(  subset(raws, raws[,label$cno] == j)))
            }
            #全体N数（全数、回答数、個別）回答数TODO
            #全数
            #csum <- c(csum, nrow(raws))
            #回答数
            csum <- c(csum, nrow(subset(raws, ! is.na(raws[, label$cno]))))
            tn <- rbind(tn, csum)

        } else {
            tn <- table(raws[, axis], raws[,label$cno], useNA="no")
            tn <- addmargins(tn)
        }

        #tp <- 100*prop.table(tn)
        #MAの%は手動計算が必要
        tp <- tn/tn[, ncol(tn)]*100

        dimnames(tn) <- list(c(axiscate, "合計"), c( cate, "合計"))

        print(tn)
        write.table(tn, file=output, append=TRUE, quote=FALSE, sep="\t")

        dimnames(tp) <- list(c(axiscate, "合計"), c( cate, "合計"))

        print(tp)
        write.table(tp, file=output, append=TRUE, quote=FALSE, sep="\t")

    } else if (label$t == "MA") {

        for ( l in 1:length(axiscate) ) {
            row <- NULL
            
            #軸がMA
            if (isMA == TRUE) {
                subraws = subset(raws, raws[, (axisl$cno+l-1)] == 1)
            } else {
                subraws = subset(raws, raws[, axis] == l)
            }

            for (j in label$cno:label$cno2) {
                col <- subset(subraws, subraws[,j] == 1,c(j))
                row <- c(row, nrow(col))
            }
            #合計（該当数、縦/行合計）
            #全数？
            #row <- c(row, nrow(subraws))
            #回答数？
            row <- c(row, nrow(subset(subraws, ! is.na(subraws[, label$cno]))))
            tn <- rbind(tn, row)
        }

        #横/列合計
        csum <- NULL
        for (j in label$cno:label$cno2) {
            subraws <- subset(raws, raws[,j] == 1)
            csum <- c(csum, nrow(subraws))
        }
        
        #全体N数（全数、回答数、個別）回答数TODO
        #全数
        #csum <- c(csum, nrow(raws))
        #回答数
        csum <- c(csum, nrow(subset(raws, ! is.na(raws[, label$cno]))))
        tn <- rbind(tn, csum)

        dimnames(tn) <- list(c(axiscate, "合計"), c( cate, "合計"))

        #MAの%は手動計算が必要
        tp <- tn/tn[, ncol(tn)]*100

        print(tn)
        write.table(tn, file=output, append=TRUE, quote=FALSE, sep="\t")

        dimnames(tp) <- list(c(axiscate, "合計"), c( cate, "合計"))

        print(tp);
        write.table(tp, file=output, append=TRUE, quote=FALSE, sep="\t")

    } else if (label$t == "NU") {
    
        for ( l in 1:length(axiscate) ) {
            if (isMA == TRUE) {
                subraws = subset(raws, raws[, (axisl$cno+l-1)] == 1)
            } else {
                subraws = subset(raws, raws[, axis] == l)
            }

            nus <- subraws[, label$cno]
            tn <- rbind(tn, c(min(nus), max(nus), mean(nus), median(nus), sum(nus), sd(nus)))

        }

        dimnames(tn) <- list(axiscate, c("最小", "最大", "平均", "中央", "合計", "標準偏差"))

        print(tn);
        write.table(tn, file=output, append=TRUE, quote=FALSE, sep="\t")

    }

}

close(output)
